// app.js
import {
  BASEAPIAIIIIN
} from './api/config/config'
const sdk = require('./lib/oreyunwx.min')
const util = require('./utils/util')
const Hub = require("./utils/miniProgramSignalr.js")

import {
  getID
} from './api/globalApi'
import {
  globalApi,
  login
} from "./api/index";
import {
  ENV
} from "./api/config/env"
App({
  globalData: {
    navHeight: 0, // 声明一个全局变量用于记录小程序头部的高度
    IMGBASEURL: 'https://staticimg.aiiiin.com/wxapp/',
    sdk,
    userStatus: {},
    canOpen: true
  },
  onLaunch() {
    if (ENV == 'production') {
      //热云
      sdk.init('14b673dde693189dea660e33a3ccda83', '', {});
    }else{
      wx.setStorageSync('token', 'Bearer 01D88658E818B6097462716F9020ACBE368B2F87D9953A91B538D1F3A75DFAA2')
    }
    let menuButtonObject = wx.getMenuButtonBoundingClientRect();
    wx.getSystemInfo({
      success: res => {
        this.globalData.navHeight = res.statusBarHeight + 44; // 赋值导航高度
        // 导航高度
        let statusBarHeight = res.statusBarHeight,
          navTop = menuButtonObject.top,
          // 胶囊按钮与右侧的距离=windowWidth-right+胶囊宽度
          navObjWid = res.windowWidth - menuButtonObject.right + menuButtonObject.width,
          navHeightM = statusBarHeight + menuButtonObject.height + (menuButtonObject.top - statusBarHeight) * 2;
        this.globalData.navHeightM = navHeightM; //导航栏总体高度
        this.globalData.navTop = navTop; //胶囊距离顶部距离
        this.globalData.navObj = menuButtonObject.height; //胶囊高度
        this.globalData.navObjWid = navObjWid; //胶囊宽度（包括右边距离)
        this.globalData.windowWidth = res.windowWidth;
        this.globalData.windowHeight = res.windowHeight;
        this.globalData.statusBarHeight = res.statusBarHeight;
      },
      fail(err) {
        console.log(err)
      }
    })
    // 登录
    const token = wx.getStorageSync('token')
    if (token) {
      this.dailylogin()
      this.getUser().then()
      this.loadSignalR()
    }
    // 小程序自动更新
    this.autoUpdate()
    // 生成全局永久设备uuid并永久保存
    if (!wx.getStorageSync('wxuuid')) {
      wx.setStorageSync('wxuuid', util.wxuuid())
    }

  },
  // 小程序自动更新检测
  autoUpdate() {
    let _this = this
    //兼容性测试
    if (wx.canIUse('getUpdateManager')) {
      const updateManager = wx.getUpdateManager()
      //监听小程序是否有新版本
      updateManager.onCheckForUpdate(res => {
        if (res.hasUpdate) {
          //下载新版并更新
          _this.downloadAndUpdate(updateManager)
        }
      })
    }
  },
  // 下载新版小程序并重启小程序
  downloadAndUpdate(updateManager) {
    wx.showLoading({
      title: '正在更新最新版小程序'
    })
    updateManager.onUpdateReady(() => {
      updateManager.applyUpdate()
    })
    updateManager.onUpdateFailed(() => {
      wx.showModal({
        title: '更新失败',
        content: "更新失败,请稍后重试",
        showCancel: false,
        success() {
          wx.hideLoading()
        }
      })
    })
  },
  getUser: async function () {
    return new Promise((resolve, reject) => {
      globalApi.getuserbaseinformation().then((rr) => {

        globalApi.getUserinfoForToken({
          ActivePort: 3
        }).then(res => {
          if (res.StatusCode === 200) {
            if (res.Message === '用户不存在') {
              wx.showToast({
                title: res.Message,
              })
              reject(false)
              return
            }
            const result = {
              ...res.Result,
              IsNewUser: rr.Result.IsNewUser
            }
            wx.setStorageSync('userInfo', result)
            resolve(result)

          } else {
            wx.showToast({
              title: '用户信息获取失败',
            })
            reject(false)
          }
        }).catch(err => {
          reject(false)
        })
      }).catch(() => {
        reject(false)
      })
    })
  },
  dailylogin: function () {
    globalApi.dailylogin()
  },
  wxfastLogin() {
    return new Promise((resolve, reject) => {
      wx.login({
        success: (res) => {
          login.phoneAndWxLogin({
            code: res.code,
            client_id: 'House_App',
            scope: 'house openid profile',
            grant_type: 'miniprogram'
          }).then((res) => {
            if (res) {
              wx.setStorageSync('token', `${res.token_type} ${res.access_token}`)
              this.dailylogin()
              this.getUser().then((res) => {
                if (res.IsNewUser) {
                  sdk.register(res.UserId, {
                    "age": 20
                  })
                } else {
                  sdk.loggedin(res.UserId, {
                    "age": 20
                  })
                }
                wx.hideLoading()
                resolve(true)
              }).catch(err => {
                reject(false)
                wx.hideLoading()
              })
            }
          }).catch((err) => {
            reject(false)
            wx.hideLoading()
          })
        },
        fail: (res) => {
          reject(false)
          wx.hideLoading()
        }
      })
    })
  },
  getUserStatus(that) {
    let _this = this
    return new Promise((resolve, reject) => {
      globalApi.getuserstatusasync().then(el => {
        if (el.StatusCode === 200) {
          if (el.Result.UserInfoStatus !== 0) {
            if (!this.globalData.canOpen) return
            const popup = that?.selectComponent('#disablePanel');
            popup?.handlePopup(el.Result.UserInfoStatus)
          }
          _this.globalData.userStatus = el.Result
          resolve(el.Result)
          if (el.Result.UserInfoStatus === 8) {
            wx.clearStorageSync()
          }
        } else {
          reject(false)
        }
      })
    })
  },
  loadSignalR() {
    wx.login({
      success: (res) => {
        let _this = this
        getID({
          code: res.code
        }).then(r => {
         
          let url = `${BASEAPIAIIIIN}/Notifications`
          this.hubConnect = new Hub.HubConnection();
          this.hubConnect.start(url, {
            ClientType: 'WXAPPLET',
            "CTL-DEVID": r.unionid
          });
          this.hubConnect.on("UserInfoStatusNotice", res => {
            _this.globalData.canOpen = true
            if (res.UserInfoStatus == 8) {
              wx.clearStorageSync()
              wx.switchTab({
                url: '/pages/ai/index'
              })
              _this.hubConnect.close({
                reason: "Server returned an error on close"
              })
            }
          })
        })
      },
    })
  }
})